package by.blog.web.servlets;

import by.blog.dao.beans.Film;
import by.blog.service.CategoryService;
import by.blog.service.FilmService;
import by.blog.service.UserService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *web.xml: /menu.jsp
 * This class execute all user actions from simple film form(single.jsp)
 * -->/main.jsp
 */
public class FilmController extends HttpServlet {

    private Film film;
    FilmService filmService;
    CategoryService categoryService;
    UserService userService;


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        String action = request.getParameter("action");
        filmService = new FilmService();


        //Converter converter=new Converter();


        if ("edit".equals(action)) {

            film = createFilmByForm(request, response);

            //film = converter.createFilmByForm(request, response);
            filmService.updateUnit(film);
        }

        if ("add".equals(action)) {

            film = createFilmByForm(request, response);

            //film = converter.createFilmByForm(request, response);
            filmService.createUnit(film);
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher("/main.jsp");
        dispatcher.forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    private Film createFilmByForm(HttpServletRequest request, HttpServletResponse response) {

        film = new Film();
        categoryService = new CategoryService();
        userService = new UserService();

        int id=0;
        try {
            id = Integer.parseInt(request.getParameter("id"));
            film.setFilm_id(id);
        }
        catch (NumberFormatException e) {

        }
        String film_name = request.getParameter("name");
        String category_name = request.getParameter("category");  // попробовать передать сразу id
        String user_name = request.getParameter("user");

        film.setFilm_name(film_name);
        film.setCategory_id(categoryService.readUnit(category_name).getCategory_id());
        film.setUser_name(userService.readUnit(user_name).getUser_name());
        return film;
    }


}
